package com.example.aussiehealthhelper;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.material.textfield.TextInputEditText;

public class DrugEditActivity extends AppCompatActivity {

    private HealthDbHelper dbHelper;
    private int drugId = -1; //-1表示添加新药品
    private TextInputEditText etDrugNameCN, etDrugNameEN, etIndication, etAdverseReaction;
    private TextInputEditText etSimilarDrugs, etDosage, etNote;
    private Spinner spinnerCategory; //下拉选择器

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_drug_edit);

        dbHelper = new HealthDbHelper(this);

        etDrugNameCN = findViewById(R.id.etDrugNameCN);
        etDrugNameEN = findViewById(R.id.etDrugNameEN);
        etIndication = findViewById(R.id.etIndication);
        etAdverseReaction = findViewById(R.id.etAdverseReaction);
        etSimilarDrugs = findViewById(R.id.etSimilarDrugs);
        etDosage = findViewById(R.id.etDosage);
        etNote = findViewById(R.id.etNote);
        spinnerCategory = findViewById(R.id.spinnerCategory);

        //下拉菜单：11个分类
        ArrayAdapter<String> categoryAdapter = new ArrayAdapter<>(
                this,
                android.R.layout.simple_spinner_item,
                HealthDbHelper.INDICATION_CATEGORIES
        );
        categoryAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerCategory.setAdapter(categoryAdapter);

        //获取传递的药品ID
        drugId = getIntent().getIntExtra("drug_id", -1);

        //如果是编辑模式，加载药品数据并显示删除按钮
        if (drugId != -1) {
            findViewById(R.id.tvEditTitle).setVisibility(View.VISIBLE);
            findViewById(R.id.btnDeleteDrug).setVisibility(View.VISIBLE);
            loadDrugData();
        }

        //保存按钮
        findViewById(R.id.btnSaveDrug).setOnClickListener(v -> saveDrug());

        //删除按钮
        findViewById(R.id.btnDeleteDrug).setOnClickListener(v -> showDeleteConfirmation());
    }

    //加载药品数据
    private void loadDrugData() {
        Drug drug = dbHelper.getDrugById(drugId);
        if (drug != null) {
            etDrugNameCN.setText(drug.getNameCN());
            etDrugNameEN.setText(drug.getNameEN());
            etIndication.setText(drug.getIndication());
            etAdverseReaction.setText(drug.getAdverseReaction());
            etSimilarDrugs.setText(drug.getSimilarDrugs());
            etDosage.setText(drug.getDosage());
            etNote.setText(drug.getNote());

            //设置下拉菜单选中当前类别
            String category = drug.getIndicationCategory();
            if (category != null && !category.isEmpty()) {
                for (int i = 0; i < HealthDbHelper.INDICATION_CATEGORIES.length; i++) {
                    if (HealthDbHelper.INDICATION_CATEGORIES[i].equals(category)) {
                        spinnerCategory.setSelection(i);
                        break;
                    }
                }
            }
        }
    }

    //保存药品
    private void saveDrug() {
        //获取输入值
        String nameCN = etDrugNameCN.getText().toString().trim();
        String nameEN = etDrugNameEN.getText().toString().trim();
        String indication = etIndication.getText().toString().trim();
        String adverse = etAdverseReaction.getText().toString().trim();
        String similar = etSimilarDrugs.getText().toString().trim();
        String dosage = etDosage.getText().toString().trim();
        String note = etNote.getText().toString().trim();

        //获取选中的类别
        String indicationCategory = spinnerCategory.getSelectedItem().toString();

        //验证输入
        if (TextUtils.isEmpty(nameCN)) {
            etDrugNameCN.setError("请输入药品中文名");
            return;
        }

        if (TextUtils.isEmpty(nameEN)) {
            etDrugNameEN.setError("请输入药品英文名");
            return;
        }


        Drug drug;
        if (drugId == -1) {
            //新药品：使用全参数构造函数
            drug = new Drug(
                    0, //ID由数据库自动生成
                    nameCN,
                    nameEN,
                    indication,
                    indicationCategory,
                    adverse,
                    similar,
                    dosage,
                    note,
                    false // 默认不收藏
            );
        } else {
            //更新现有药品：使用完整版构造函数
            drug = new Drug(
                    drugId,
                    nameCN,
                    nameEN,
                    indication,
                    indicationCategory,
                    adverse,
                    similar,
                    dosage,
                    note,
                    false // 保留原始收藏状态
            );
        }

        //保存到数据库
        if (drugId == -1) {
            //添加新药品
            long result = dbHelper.addDrug(drug);
            if (result != -1) {
                Toast.makeText(this, "药品添加成功", Toast.LENGTH_SHORT).show();
                finish();
            } else {
                Toast.makeText(this, "添加失败，请重试", Toast.LENGTH_SHORT).show();
            }
        } else {
            //更新现有药品
            int result = dbHelper.updateDrug(drug);
            if (result > 0) {
                Toast.makeText(this, "药品更新成功", Toast.LENGTH_SHORT).show();
                finish();
            } else {
                Toast.makeText(this, "更新失败，请重试", Toast.LENGTH_SHORT).show();
            }
        }
    }

    //显示删除确认对话框
    private void showDeleteConfirmation() {
        new AlertDialog.Builder(this)
                .setTitle("删除药品")
                .setMessage("确定要删除这个药品吗？此操作不可撤销。")
                .setPositiveButton("删除", (dialog, which) -> deleteDrug())
                .setNegativeButton("取消", null)
                .show();
    }

    //删除药品
    private void deleteDrug() {
        int result = dbHelper.deleteDrug(drugId);
        if (result > 0) {
            Toast.makeText(this, "药品删除成功", Toast.LENGTH_SHORT).show();
            finish();
        } else {
            Toast.makeText(this, "删除失败，请重试", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (dbHelper != null) {
            dbHelper.close();
        }
    }
}